const mysqlUtil = require('../util/mysqlUtil');
const superagent = require('superagent');

/**
 * 定时通知测试人员验证测试包
 */
module.exports = function() {
    setInterval(function() {
        var date = new Date();
        if (date.getHours() !== 13 && date.getHours() !== 17) {
            return;
        }

        var dateStr = getDay(0, '-');
        var sql = `
			select code, name, tel, sum(c) c, group_concat(distinct svn_message) as svn_message
			from (
				select u.code, u.name, u.tel, l.svn_message, (select count(1) from svn_log_path lp where lp.svn_revision=l.svn_revision) c
				from svn_user u
				left join svn_log l on l.svn_author=u.code and l.svn_date like '{{dateStr}}%'
			) datas group by code, name, tel
			order by sum(c) desc
        `;
        sql = sql.replace('{{dateStr}]', dateStr);

        mysqlUtil.exec(sql, [], function(err, result) {
            var content = '';
            var tels = [];
            for (var i = 0; i < result.length; i++) {
                var res = result[i];
                content += '@' + res.tel + ' ';
                tels.push(res.tel);
            }

            content += '\n今天截止到当前，\n\n'
            for (var i = 0; i < result.length; i++) {
                var res = result[i];
                content += '' + res.name + '已更新提交' + res.c + '个文件，大概修改内容为“' + (res.svn_message || '无') + '”；\n\n';
            }

            content += '大家继续努力哦！!\n（数据存在延迟情况，仅供参考）';

            superagent.post('https://oapi.dingtalk.com/robot/send?access_token=207bb34283a65d0a5802516e2d698e3c6ea6912add990f40f1bc237522d5121c').send({
                "msgtype": "text",
                "text": {
                    "content": content
                },
                "at": {
                    "atMobiles": tels,
                    "isAtAll": false
                }
            }).end(function(err, res) {
                console.log('ok!');
            });
        });
    }, 1000 * 60 * 60);
}

function getDay(num, str) {
    var today = new Date();
    var nowTime = today.getTime();
    var ms = 24 * 3600 * 1000 * num;
    today.setTime(parseInt(nowTime + ms));
    var oYear = today.getFullYear();
    var oMoth = (today.getMonth() + 1).toString();
    if (oMoth.length <= 1) {
        oMoth = '0' + oMoth;
    }
    var oDay = today.getDate().toString();
    if (oDay.length <= 1) {
        oDay = '0' + oDay;
    }
    return oYear + str + oMoth + str + oDay;
}